package 多窗口卖票.多线程的同步方法机制;

/**
 * 利用同步方法处理Runnable线程的安全问题
 */

class MyThread implements Runnable{
    private int ticket=100;
    private boolean isFlag=true;
    @Override
    public void run() {
        while (isFlag){

            show();

        }
    }

    //创建一个私有同步方法
    private synchronized boolean show(){//同步监视器为当前类MyThread类或this;
        if (ticket >= 0) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("卖的票号：" + ticket);
            ticket--;
        } else {
            isFlag=false;
        }
        return isFlag;
    }
}

public class Test3 {
    public static void main(String[] args) {
        MyThread mt1 = new MyThread();//只有一个对象

        Thread t1 = new Thread(mt1);
        Thread t2 = new Thread(mt1);
        Thread t3 = new Thread(mt1);

        t1.start();
        t2.start();
        t3.start();
    }
}
